<template>
  <view class="my-page page-container">
    <view class="top">
      <view class="profile" @click="showActionSheet = true">
        <image class="avatar" :src="headimg" mode="aspectFill" />
        <view class="info">
          <text class="phone">{{ userName || '未设置昵称' }}</text>
          <view class="meta-row">
            <text class="meta-text">UID：{{ ID || '未登录' }}</text>
          </view>
          <view class="meta-row">
            <text class="meta-text">邀请码：{{ inviteCode || '-' }}</text>
            <text class="meta-text meta-right">积分：{{ points || 0 }}</text>
          </view>
          <view class="meta-row">
            <text class="meta-text">注册时间：{{ registerTime || '-' }}</text>
          </view>
        </view>
      </view>

      <view class="vip-card" @click="goToRecharge">
        <image class="vip-icon" src="/static/images/user-v2/icon-vip-badge.png" mode="widthFix" />
        <text class="vip-text">解锁高级服务 尊享专属权益</text>
        <view class="vip-btn">解锁高级服务</view>
      </view>
    </view>

    <view class="menu">
      <view class="menu-item" @click="showPushPicker = true">
        <image class="icon" src="/static/images/user-v2/icon-bell.png" mode="widthFix" />
        <text class="label">订阅提醒</text>
        <view class="chevron">
          <uv-icon name="arrow-right" size="18"></uv-icon>
        </view>
      </view>
      <view class="menu-item" @click="goToInvite">
        <image class="icon" src="/static/images/user-v2/icon-invite.png" mode="widthFix" />
        <text class="label">邀请好友</text>
        <view class="chevron">
          <uv-icon name="arrow-right" size="18"></uv-icon>
        </view>
      </view>
      <view class="menu-item" @click="goToFAQ">
        <image class="icon" src="/static/images/user-v2/icon-faq.png" mode="widthFix" />
        <text class="label">常见问题</text>
        <view class="chevron">
          <uv-icon name="arrow-right" size="18"></uv-icon>
        </view>
      </view>
      <view class="menu-item" @click="goToFeedback">
        <image class="icon" src="/static/images/user-v2/icon-feedback.png" mode="widthFix" />
        <text class="label">意见反馈</text>
        <view class="chevron">
          <uv-icon name="arrow-right" size="18"></uv-icon>
        </view>
      </view>
      <view class="menu-item" @click="goToCustomerService">
        <image class="icon" src="/static/images/user-v2/icon-support.png" mode="widthFix" />
        <text class="label">联系客服</text>
        <view class="chevron">
          <uv-icon name="arrow-right" size="18"></uv-icon>
        </view>
      </view>
      <view class="menu-item" @click="goToPrivacy">
        <image class="icon" src="/static/images/user-v2/icon-privacy.png" mode="widthFix" />
        <text class="label">隐私政策</text>
        <view class="chevron">
          <uv-icon name="arrow-right" size="18"></uv-icon>
        </view>
      </view>
      <view class="menu-item" @click="goToAccountSafe">
        <image class="icon" src="/static/images/user-v2/icon-settings.png" mode="widthFix" />
        <text class="label">修改密码</text>
        <view class="chevron">
          <uv-icon name="arrow-right" size="18"></uv-icon>
        </view>
      </view>
      <view class="menu-item last" @click="goToSystemSettings">
        <image class="icon" src="/static/images/user-v2/icon-settings.png" mode="widthFix" />
        <text class="label">系统设置</text>
        <view class="chevron">
          <uv-icon name="arrow-right" size="18"></uv-icon>
        </view>
      </view>
    </view>

    <view class="logout-section">
      <view class="logout-btn" @click="onLogout(false)">
        <text class="logout-text">退出登录</text>
      </view>
    </view>

    <!-- 头像操作弹窗 -->
    <uv-action-sheet
      v-model="showActionSheet"
      :actions="actions"
      @select="onActionSelect"
      cancel-text="取消"
      close-on-click-action
    />

    <!-- 修改昵称弹窗 -->
    <uv-popup
      v-model="showNickDialog"
      mode="center"
      :close-on-click-overlay="true"
      border-radius="20"
    >
      <view class="nick-dialog">
        <text class="dialog-title">修改昵称</text>
        <view class="dialog-content">
          <uv-input
            v-model="newNick"
            placeholder="请输入昵称"
            maxlength="20"
            :custom-style="dialogInputStyle"
          />
        </view>
        <view class="dialog-buttons">
          <uv-button
            type="primary"
            :loading="loading"
            @click="saveNickName"
            :custom-style="dialogButtonStyle"
          >
            提交
          </uv-button>
        </view>
      </view>
    </uv-popup>

    <!-- 推送配置弹窗 -->
    <uv-popup
      v-model="showPushPicker"
      mode="bottom"
      height="70%"
      border-radius="20"
      closeable
      @open="showStateToast"
    >
      <view class="push-config">
        <view class="push-header">
          <text class="push-title">推送配置</text>
          <uv-button
            type="primary"
            @click="updatePushStateBatch"
            :loading="pushLoading"
            size="small"
          >
            确定
          </uv-button>
        </view>
        <view class="push-content">
          <uv-checkbox-group v-model="selectedPushOptions">
            <view class="checkbox-item" v-for="item in pushColumns" :key="item.value">
              <uv-checkbox
                :name="item.value"
                shape="square"
              >
                {{ item.text }}
              </uv-checkbox>
            </view>
          </uv-checkbox-group>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { logout } from '@/api/auth'
import { saveNickName, savePushState, getPushState, postPushState, putPushStateBatch, getMyInfo } from '@/api/user'

export default {
  name: 'MyPage',
  data() {
    return {
      info: {},
      loading: false,
      showActionSheet: false,
      newNick: '',
      showNickDialog: false,
      pushState: '',
      showPushPicker: false,
      selectedPushOptions: [],
      pushLoading: false,
      inviteCode: '',
      points: 0,
      registerTime: '',
      pushColumns: [
        { text: '5分钟推送', value: '1' },
        { text: '15分钟推送', value: '2' },
        { text: '30分钟推送', value: '3' },
        { text: '一小时推送', value: '4' },
        { text: '两小时推送', value: '7' },
        { text: '四小时推送', value: '5' },
        { text: '六小时推送', value: '8' },
        { text: '十二小时推送', value: '9' },
        { text: '一天推送', value: '6' },
      ],
      actions: [
        { name: '上传头像' },
        { name: '修改昵称' },
      ],
      // 这些数据将从Vuex状态中获取，不需要在data中定义
      // ID, VIP, nickName, userName, avatarImg, memberEndTime 通过 mapState 获取
      dialogInputStyle: {
        border: '1px solid #ddd',
        borderRadius: '8px',
        padding: '12px',
        marginBottom: '20px'
      },
      dialogButtonStyle: {
        width: '100%',
        height: '44px'
      }
    }
  },
  created() {
    this.loadUserInfo()
  },
  computed: {
    ...mapState('user', ['ID', 'VIP', 'nickName', 'userName', 'avatarImg', 'memberEndTime']),
    headimg() {
      return this.avatarImg || '/static/images/user-v2/avatar-default.png'
    },
    pushStateDesc() {
      if (!this.pushState) {
        return ''
      }
      if (this.pushState == 'YES') {
        return ''
      }
      if (this.pushState == 'NO15M') {
        return ''
      }
      return ''
    }
  },
  methods: {
    ...mapActions('user', ['fedLogOut', 'setNickName']),
    loadUserInfo() {
      getMyInfo().then(response => {
        this.pushState = response.data.pushState
        if (!this.pushState) {
          this.pushState = 'YES'
        }
        // 获取邀请码、积分、注册时间等信息
        this.inviteCode = response.data.inviteCode || ''
        this.points = response.data.points || 0
        this.registerTime = response.data.registerTime || ''
      }).catch(error => {
        console.error('获取用户信息失败:', error)
        // 设置默认值
        this.pushState = 'YES'
      })
    },

    // 跳转到客服页面
    goToCustomerService() {
      uni.navigateTo({
        url: '/subPages/help/customer-service'
      })
    },

    async onLogout(confirmed) {
      if (!confirmed) {
        uni.showModal({
          title: '提示',
          content: '确认退出吗？',
          success: (res) => {
            if (res.confirm) {
              this.onLogout(true)
            }
          }
        })
        return
      }

      // 显示加载提示
      uni.showLoading({
        title: '退出中...',
        mask: true
      })

      try {
        // 异步调用退出登录接口
        await this.fedLogOut()
        
        uni.hideLoading()
        uni.showToast({
          title: '退出成功',
          icon: 'none',
          duration: 1500
        })
        
        setTimeout(() => {
          uni.reLaunch({ url: '/subPages/auth/login' })
        }, 1500)
      } catch (err) {
        console.error('退出登录失败:', err)
        uni.hideLoading()
        // 即使失败也清除本地数据并跳转到登录页
        this.$store.commit('user/CLEAR_USER_INFO')
        this.$store.commit('token/CLEAR_TOKEN')
        uni.reLaunch({ url: '/subPages/auth/login' })
      }
    },

    onActionSelect(item, index) {
      this.showActionSheet = false
      if (index == 1) {
        this.newNick = ''
        this.showNickDialog = true
      } else if (index == 0) {
        this.goToHeadImg()
      }
    },

    saveNickName() {
      if (!this.newNick.trim()) {
        uni.showToast({
          title: '请输入昵称',
          icon: 'none'
        })
        return
      }

      this.loading = true

      saveNickName(this.newNick).then(() => {
        this.setNickName(this.newNick)
        this.showNickDialog = false
        this.loading = false
        uni.showToast({
          title: '修改成功',
          icon: 'none'
        })
      }).catch(err => {
        uni.showToast({
          title: err || '修改失败',
          icon: 'none'
        })
        this.loading = false
      })
    },

    showStateToast() {
      // 清空选中状态
      this.selectedPushOptions = []

      getPushState().then((res) => {
        if (res.data) {
          const str = String(res.data)
          const arr = str.split(",")
          // 将选中的值添加到selectedPushOptions数组中
          this.selectedPushOptions = arr.filter(item => item && item.trim() !== '')
        }
      }).catch(error => {
        console.error('获取推送状态失败:', error)
      })
    },

    updatePushStateBatch() {
      this.pushLoading = true

      // 将选中的值转换为逗号分隔的字符串
      let arr = this.selectedPushOptions.join(',')
      if (arr === '') {
        arr = ','
      } else {
        arr = arr + ','
      }

      putPushStateBatch(arr).then(() => {
        this.pushLoading = false
        this.showPushPicker = false
        uni.showToast({
          title: '修改成功',
          icon: 'none'
        })
      }).catch(err => {
        this.pushLoading = false
        uni.showToast({
          title: err || '修改失败',
          icon: 'none'
        })
      })
    },

    goToRecharge() {
      // TODO: 跳转到充值页面
      uni.showToast({
        title: '跳转到充值页面',
        icon: 'none'
      })
    },

    goToAccountSafe() {
      // TODO: 跳转到安全中心页面
      uni.showToast({
        title: '跳转到安全中心',
        icon: 'none'
      })
    },

    goToHeadImg() {
      // TODO: 跳转到头像上传页面
      uni.showToast({
        title: '跳转到头像上传',
        icon: 'none'
      })
    },

    goToInvite() {
      uni.showToast({
        title: '跳转到邀请好友',
        icon: 'none'
      })
    },

    goToFAQ() {
      uni.showToast({
        title: '跳转到常见问题',
        icon: 'none'
      })
    },

    goToFeedback() {
      uni.showToast({
        title: '跳转到意见反馈',
        icon: 'none'
      })
    },

    goToPrivacy() {
      uni.showToast({
        title: '跳转到隐私政策',
        icon: 'none'
      })
    },

    goToSystemSettings() {
      uni.showToast({
        title: '跳转到系统设置',
        icon: 'none'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.my-page {
  box-sizing: border-box;
  padding-bottom: 40rpx;
  background-color: #f8f8f8;
}

.top {
  height: 420rpx;
  padding: 40rpx 24rpx 24rpx;
  padding-top: calc(40rpx + var(--status-bar-height));
  background: url('/static/images/user-v2/my-header-bg.png') no-repeat top center;
  background-size: 100% auto;
}

.profile {
  display: flex;
  align-items: center;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  margin-right: 24rpx;
  background-color: #fff;
  border-radius: 50%;
}

.info {
  display: flex;
  flex-direction: column;
}

.phone {
  font-size: 32rpx;
  font-weight: 600;
  color: #0e1e25;
  margin-bottom: 8rpx;
}

.meta-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 6rpx;
}

.meta-text {
  font-size: 24rpx;
  color: #5e6c74;
}

.meta-right {
  margin-left: 20rpx;
}

.meta {
  margin: 8rpx 0;
}

.uid {
  margin-right: 16rpx;
  font-size: 26rpx;
  color: #5e6c74;
}

.vip-badge {
  padding: 2rpx 12rpx;
  font-size: 20rpx;
  color: #fff;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12rpx;
  margin-left: 16rpx;
}

.expire {
  font-size: 26rpx;
  color: #5e6c74;
}

.value {
  font-size: 28rpx;
  color: #999;
  margin-right: 16rpx;
}

.vip-card {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 26rpx 24rpx;
  margin-top: 34rpx;
  background: url('/static/images/user-v2/my-bg.png') no-repeat;
  background-size: 100% 100%;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(6, 203, 182, 0.15);
}

.vip-icon {
  width: 50rpx;
  height: 40rpx;
  margin-right: 12rpx;
}

.vip-text {
  flex: 1;
  margin-left: 12rpx;
  font-size: 28rpx;
  font-weight: 600;
  color: #fff;
}

.vip-btn {
  padding: 10rpx 22rpx;
  font-size: 24rpx;
  font-weight: 600;
  color: #fff;
  background: #cebafc;
  border-radius: 999rpx;
}

.menu {
  margin: 24rpx;
  margin-top: -50rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 12rpx 40rpx rgba(16, 30, 36, 0.06);
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 32rpx 40rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.menu-item.last {
  border-bottom: none;
}

.icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 28rpx;
}

.label {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  font-weight: 400;
}

.chevron {
  display: flex;
  align-items: center;
  color: #999;
}

/* 弹窗样式 */
.nick-dialog {
  padding: 40rpx;
  width: 600rpx;
  background: #fff;
  border-radius: 20rpx;
}

.dialog-title {
  display: block;
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 40rpx;
}

.dialog-content {
  margin-bottom: 40rpx;
}

.dialog-buttons {
  margin-top: 20rpx;
}

.push-config {
  padding: 40rpx;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.push-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.push-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.push-content {
  flex: 1;
  overflow-y: auto;
}

.checkbox-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }
}

.logout-section {
  margin: 24rpx;
  margin-top: 20rpx;
}

.logout-btn {
  background: #fff;
  border-radius: 20rpx;
  padding: 32rpx 40rpx;
  text-align: center;
  box-shadow: 0 12rpx 40rpx rgba(16, 30, 36, 0.06);
}

.logout-text {
  font-size: 32rpx;
  color: #333;
  font-weight: 400;
}
</style>
